package com.suntech.lanq
{
	import flash.events.DatagramSocketDataEvent;
	import flash.events.Event;
	import flash.net.DatagramSocket;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;

	import mx.controls.Alert;
	import mx.logging.Log;

	public class UDPsocket
	{
		public var datagramSocket:DatagramSocket=new DatagramSocket();
		[Inject]
		public var main:Main;

		[Inject]
		public var logTarget:LogTarget;

		public function UDPsocket()
		{
		}

		public function bind(port:int, ip:String):void
		{

			if (datagramSocket.bound)
			{
				datagramSocket.close();
				datagramSocket=new DatagramSocket();

			}
			datagramSocket.bind(port, ip);
			datagramSocket.addEventListener(DatagramSocketDataEvent.DATA, dataReceived);
			datagramSocket.receive();
			//Log.getLogger(logTarget.logFilter).info("udp绑定: " + datagramSocket.localAddress + ":" + datagramSocket.localPort.toString());
		}

		public function dataReceived(event:DatagramSocketDataEvent):void
		{
			//Read the data from the datagram
			//Log.getLogger(logTarget.logFilter).info("udp接收到消息: " + event.srcAddress + ":" + event.srcPort.toString() + "> " + event.data.readUTFBytes(event.data.bytesAvailable));

			var udpMessage:UDPMessage=UDPMessage(event.data.readObject());
			//Alert.show("udp接收到消息: " + event.srcAddress + ":" + event.srcPort.toString() + "> " + udpMessage.type);
			if(udpMessage.type==UDPMessage.ONLINE){
				
			}else if(udpMessage.type==UDPMessage.ONLINE){
				
			}else if(udpMessage.type==UDPMessage.ONLINE){
				
			}else{
				Alert.show("UDPsocket received an unknown message!!!");
			}
		}

		public function send(message:UDPMessage, targetIP:String, targetPort:int):void
		{
			//Create a message in a ByteArray
			//trace("==="+message);
			var data:ByteArray=new ByteArray();
			registerClassAlias("com.suntech.lanq.UDPMessage", UDPMessage);

			data.writeObject(message)
			data.position=0;
			//data.writeUTFBytes(message);

			//Send a datagram to the target
			try
			{
				datagramSocket.send(data, 0, 0, targetIP, targetPort);
					//Log.getLogger(logTarget.logFilter).info("udp发送消息到: " + targetIP.toString() + ":" + targetPort.toString());
			}
			catch (error:Error)
			{
				//Log.getLogger(logTarget.logFilter).info("udp错误: " + error.message);
			}
		}
	}
}
